package app.TouTiao;

import qiurank.Log;
import qiurank.UrlManageFather;
import qiurank.UrlManageInterface;
import qiurank.UrlObject;

/**
 * Created by Administrator on 2016/1/14.
 */
public class UrlManage extends UrlManageFather implements UrlManageInterface{
    private UrlModel urlModel;
    public UrlManage(){
        super();
    }

    @Override
    public int getYesUrlCount() {
        return urlModel.getYesUrlCount();
    }

    @Override
    protected void setNoUrlList() {
        urlModel=new UrlModel();
        noUrl=urlModel.getNoUrlList();
    }

    @Override
    public UrlObject getNoUrl() {
        int len=noUrl.size();
        if(len>0) {
            return plan.doPlanGetNoPaUrl(noUrl); //使用url策略进行取url
        }else{
            noUrl=urlModel.getNoUrl();
            if(noUrl.size()>0){
                return plan.doPlanGetNoPaUrl(noUrl); //使用url策略进行取url
            }else {
                UrlObject _urlObject=new UrlObject();
                _urlObject.key=0;
                _urlObject.url=Config.BASE_URL;
                return _urlObject;
            }
        }
    }

    @Override
    public boolean setPa(UrlObject urlObject) {
        if(urlObject!=null) {
            if(noUrl.contains(urlObject)){
                urlModel.setPa(urlObject);
                noUrl.remove(urlObject);

                Log.show(urlObject.key + "-" + urlObject.url + "已经从待爬取中移除,并放入到已爬取队列里");
                return true;
            }
        }else{
            Log.show("要将:urlObject对象为空--失败");
        }
        return  false;
    }
    /**
     * 添加url到待爬取列表，需要判断该url是否存在，不存在则添加进去，
     * @param url 待添加的url
     * @param weight url权重值
     * @return  添加成功返回true，失败返回false
     */
    public boolean addUrl(String url,int weight){
        if(plan.doPlanAddUrl(url)) {
            UrlObject urlObject = urlModel.addUrl(url,weight);
            if (urlObject != null) {
                if(noUrl.size()<100&&isExist(urlObject)==false) {
                    noUrl.add(urlObject);
                }
                return true;
            } else {
                Log.show("URL:" + url + ",已经存在,添加失败");
                return false;
            }
        }else{
            Log.show("URL:" + url + ",不符合URL规则,添加失败");
            return  false;
        }
    }
}
